package com.aysafety.iotdataplatformserver.listener;

import com.aysafety.core.DBDriver.hbase.HBaseDriver;
import com.aysafety.core.common.Common;
import com.aysafety.core.common.DateUtils;
import com.aysafety.core.model.ErrorModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class ErrorListener {

    private final String tableName = "IotLog";

    private final String[] structure = new String[] {"ERROR", "INFO", "DEBUG"};

    private Logger logger = LoggerFactory.getLogger(ErrorListener.class);

    public void start(Map<String, Object> result) {
        try {
            ErrorModel errorModel = this.transformData(result);
            this.save(errorModel);
        } catch (Exception e) {
            logger.info("ErrorListener:", e);
        }
    }

    public ErrorModel transformData(Map<String, Object> result) {
        ErrorModel errorModel = new ErrorModel();
        errorModel.setClientId(result.get("clientId").toString());
        errorModel.setData(result.get("data").toString());
        errorModel.setDataType(result.get("dataType").toString());
        errorModel.setType(result.get("type").toString());
        errorModel.setCreateDate(DateUtils.fomatDateTime(result.get("createDate").toString()));
        return errorModel;
    }

    public boolean save(ErrorModel errorModel) throws IOException {
        List<String> params = new ArrayList<String>();
        String timestamp = String.valueOf(DateUtils.fomatDateTime(DateUtils.getTime()).getTime());
        params.add(errorModel.getClientId());
        params.add(errorModel.getDataType());
        String rowKey = Common.getRowKey(params, timestamp);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("tableId", "IotLog");
        map.put("pk", "\'" + rowKey + "\'");
        map.put("clientId", "\'" + errorModel.getClientId() + "\'");
        map.put("data", "\'" + errorModel.getData() + "\'");
        map.put("dataType", "\'" + errorModel.getDataType() + "\'");
        map.put("type", "\'" + errorModel.getType() + "\'");
        map.put("createDate", "\'" + errorModel.getCreateDate() + "\'");

        return true;
    }

    public boolean createTable() throws IOException {
        return HBaseDriver.createTable(this.tableName, this.structure);
    }
}
